import 'package:flutter/material.dart';
import 'package:flutter_demo2/base/plugin/route_native/manager.dart';
import 'package:flutter_demo2/base/plugin/route_native/message_bean.dart';
// import 'package:logging/logging.dart';

// final _log = Logger('NavObserver');

final NavObserver navObserver = NavObserver();

// previousRoute指的是栈中相对的前一个route
// 可以监听所有出入栈，包括未受到自己router by name管理的栈和对话框
class NavObserver extends NavigatorObserver {
  NavObserver._internal();

  static final NavObserver _singleton = NavObserver._internal();

  factory NavObserver() => _singleton;

  final List<Route<dynamic>?> _routeStack = [];

  Route<dynamic>? get currentRoute {
    if (_routeStack.isNotEmpty) {
      return _routeStack.last;
    }
    return null;
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    // _log.info("didPush route: ${route.settings.name} previousRoute: ${previousRoute?.settings.name}");
    _routeStack.add(route);
    _sendMessage(0, route, previousRoute);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    // _log.info("didPop route: ${route.settings.name} previousRoute: ${previousRoute?.settings.name}");
    if (_routeStack.isNotEmpty) {
      _routeStack.removeLast();
    }
    _sendMessage(1, route, previousRoute);
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    // 暂时没用到
    _routeStack.removeWhere((element) => element?.settings.name == route.settings.name);
    // _log.info("didRemove route: ${route.settings.name} previousRoute: ${previousRoute?.settings.name}");
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    // _log.info("didReplace newRoute: ${newRoute?.settings.name} oldRoute: ${oldRoute?.settings.name}");
    if (_routeStack.isNotEmpty) {
      _routeStack.removeLast();
    }
    _routeStack.add(newRoute);
    _sendMessage(2, newRoute, oldRoute);
  }

  void _sendMessage(int type, Route<dynamic>? route, Route<dynamic>? previousRoute) {
    String? currentRoute = route?.settings.name;
    String? preRoute = previousRoute?.settings.name;

    var msgBean = SendMessage.flutterRouteChangeMsg(type, currentRoute, preRoute);
    RouterHelper.sendMessage(msgBean);
  }
}
